import { devtools, persist, subscribeWithSelector } from "zustand/middleware";
import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import { userLogin , getUserInfo} from "@/api";
import { cloneDeep } from "lodash";
// import { allAsyncRoutes ,anyRoute,staticRoutes} from "@/routers";
import AppRouter from "@/routers/index";

const initialState = {
  color: "red",
  cats: {
    name: '',
    accessToken: '',
    menuRoutes: [],
    routeStore:[],
  },
};
//过滤路由
function filterAsyncRoutes(allAsyncRoutes, routesName) {
  console.log(routesName,'routesName')
  // 对异步路由进行过滤
  return allAsyncRoutes.filter((route) => {
    // routesName是一维数组
    if (routesName.indexOf(route.meta.name) === -1) {
      console.log(route.meta.name,'route.meta.name')
      return false;
    }
    // 递归函数的特点：函数调函数自身，需要有跳出机制，否则死循环
    if (route.children && route.children.length > 0) {
      route.children = filterAsyncRoutes(route.children, routesName); // 递归
    }
    return true;
  });
}

function addRoutes(routes) {
  console.log(routes,'请示')
  routes.forEach((route, index) => {
    if (route.children && route.children.length > 0) {
      route.index = `${route.path}`;
      route.children.forEach((childRoute, childIndex) => {
        childRoute.index = `${route.path}/${childRoute.path}`;
      });
    } else {
      route.index = `${route.path}`;
    }
    // (route);
  });
}

// function resetRouter() {
//   const routes = AppRouter.getRoutes();
//   routes.forEach((r) => AppRouter.removeRoute(r.name));
//   staticRoutes.forEach((r) => AppRouter.addRoute(r));
// }

// 如何处理动态路由
// 动态路由
// const useRouteStore = create(
//   (set) => ({
//   routes: [cloneDeep(allAsyncRoutes)],  // 初始路由配置
//   addRoute: (newRoute) =>
//     set((state) => ({ routes: [...state.routes, newRoute] })),
//   removeRoute: (path) =>
//     set((state) => ({
//       routes: state.routes.filter((route) => route.path !== path),
//     })),
// }));

// export default useRouteStore;

export const useCatStore = create(
  immer(
    devtools(
      subscribeWithSelector(
        persist(
          //处理异步获取数据
          (set, get) => ({
            ...initialState,
            // getInfo: async () => {
            //   try {
            //     const res = await getUserInfo();
            //     const remoteRoutes = res.routes;
            //     localStorage.setItem("routes", JSON.stringify(remoteRoutes));
            //     // 循环遍历 remoteRoutes 将 routesName 转换成一维数组
            //     const routesName = remoteRoutes.map((item) => item.routeName);
               
            //     const newAsyncRoutes = filterAsyncRoutes(
            //       cloneDeep(allAsyncRoutes),
            //       routesName
            //     ); 
            //     console.log('newAsyncRoutes111', newAsyncRoutes);
            //     addRoutes([...newAsyncRoutes, anyRoute]);
            //     set((state) => {
            //       state.cats.name = res.username;
            //       state.cats.menuRoutes = [...staticRoutes, ...newAsyncRoutes];
            //     });
            //     // get().getRefreshToken();
            //     console.log(staticRoutes,'staticRoutes')
            //     console.log(get().cats.menuRoutes,'chakan123')
            //   } catch (error) {
            //     console.error('Failed to get info:', error);
            //   }
            // },
            // 添加 getRefreshToken 作为 store 的操作
            getRefreshToken: async () => {
              try {
                console.log("getRefreshToken")
                // const { accessToken, refreshToken } = await postRefreshToken(get().refreshToken);  // 使用 get() 获取当前的 refreshToken
                // set((state) => {
                //   state.accessToken = accessToken;
                //   state.refreshToken = refreshToken;
                // });
                // return accessToken;
              } catch (error) {
                console.error('获取 refreshToken 失败:', error);
              }
            },
          }),
          {
            name: "cat-store",
            partialize: (state) =>
              Object.fromEntries(
                Object.entries(state).filter(([key]) => !["color"].includes(key))
              ), // 部分化，只保存部分数据，排除不必要的内容
          }
        )
      )
    )
  )
);

// 通过外部方法增加猫的数量，方法和数据的管理分离
export const userLoginToken = async () => {
  const res = await userLogin('chinavane', 'chinavane');
  console.log(res, '登录信息');
  localStorage.setItem("token", "Bearer " + res.accessToken);
  // useCatStore.getState().getInfo();
  return res
  // useCatStore.setState((state) => {
  //   state.accessToken = "Bearer " + JSON.parse(localStorage.getItem("token") || '{}').accessToken;
  // })
}

// export const getUserInfoStore = async() =>{
//   const res = await getUserInfo()
//   console.log(res,'获取getuserinfor')
//   return res
// }
// export const increaseSmallCats = () =>
//   useCatStore.setState((state) => {
//     state.cats.smallCats++;
//   });

// export const summary = () => {
//   const state = useCatStore.getState();
//   return state.cats.bigCats + state.cats.smallCats;
// };